<template>
  <a-spin :spinning="formState.uploadImgLoading">
    <page-layout class="add-project-box">
      <a-row :gutter="[10, 10]">
        <a-col :span="24">
          <a-form
            ref="formRef"
            :model="formState.data"
            :rules="rules"
            :label-col="labelCol"
            :wrapper-col="wrapperCol"
          >
            <a-card>
              <footer-button :buttons="formState.buttons" />
              <a-row>
                <a-col :span="6">
                  <a-form-item label="是否上架" name="state">
                    <a-switch 
                      v-model:checked="formState.data.state"
                      checkedValue="yes"
                      unCheckedValue="no"
                    />
                  </a-form-item>
                </a-col>
              </a-row>
              <a-row>
                <a-col :span="6">
                  <a-form-item
                    label="编码"
                    name="code"
                  >
                    <a-input
                      readonly
                      v-model:value="formState.data.code"
                      placeholder="自动生成"
                    />
                  </a-form-item>
                </a-col>
                <a-col :span="6">
                  <a-form-item label="项目名称" name="projectName">
                    <a-input
                      class="pointer-input"
                      v-model:value="formState.data.projectName"
                      readonly
                      placeholder="请选择"
                    >
                      <template #addonAfter>
                        <div
                          class="primary-color cursor-pointer"
                          @click="openDialog('schName')"
                        >
                          选择
                        </div>
                      </template>
                    </a-input>
                  </a-form-item>
                </a-col>
                <a-col :span="6">
                  <a-form-item label="课程名称" name="cbiName">
                    <a-input
                      class="pointer-input"
                      v-model:value="formState.data.cbiName"
                      readonly
                      placeholder="请选择"
                    >
                      <template #addonAfter>
                        <div
                          class="primary-color cursor-pointer"
                          @click="openDialog('cbiName')"
                        >
                          选择
                        </div>
                      </template>
                    </a-input>
                  </a-form-item>
                </a-col>
                <a-col :span="6">
                  <a-form-item
                    label="学校班级代码"
                    name="schShiftCode"
                  >
                    <a-input
                      v-model:value="formState.data.schShiftCode"
                      placeholder="请输入"
                    />
                  </a-form-item>
                </a-col>
                <a-col :span="6">
                  <a-form-item label="最多招生人数" name="maximumEnrollment">
                    <a-input-number style="width: 100%" v-model:value="formState.data.maximumEnrollment" placeholder="请输入" :min="0" :max="1000000" />
                  </a-form-item>
                </a-col>
                <a-col :span="6">
                  <a-form-item label="价格" name="price">
                    <a-input
                      v-model:value="formState.data.price"
                      suffix="元"
                      placeholder="请输入"
                    />
                  </a-form-item>
                </a-col>
                <a-col :span="6">
                  <a-form-item label="教授" name="professorName">
                    <a-input
                      v-model:value="formState.data.professorName"
                      readonly
                      placeholder="请选择"
                    >
                      <template #addonAfter>
                        <div
                          class="primary-color cursor-pointer"
                          @click="openDialog('professorName')"
                        >
                          选择
                        </div>
                      </template>
                    </a-input>
                  </a-form-item>
                </a-col>
                <a-col :span="6">
                  <a-form-item label="助教" name="taName">
                    <a-input
                      v-model:value="formState.data.taName"
                      readonly
                      placeholder="请选择"
                    >
                      <template #addonAfter>
                        <div
                          class="primary-color cursor-pointer"
                          @click="openDialog('taName')"
                        >
                          选择
                        </div>
                      </template>
                    </a-input>
                  </a-form-item>
                </a-col>
                <a-col :span="6">
                  <a-form-item label="教材" name="teachingName">
                    <a-input
                      v-model:value="formState.data.teachingName"
                      readonly
                      placeholder="请选择"
                    >
                      <template #addonAfter>
                        <div
                          class="primary-color cursor-pointer"
                          @click="openDialog('teaching')"
                        >
                          选择
                        </div>
                      </template>
                    </a-input>
                  </a-form-item>
                </a-col>
                <a-col :span="6">
                  <a-form-item label="开始注册日期" name="startRegisterTime">
                    <a-date-picker
                      v-model:value="formState.data.startRegisterTime"
                      placeholder="选择日期"
                      valueFormat="yyyy-MM-DD"
                      type="date"
                      class="w-100p"
                    />
                  </a-form-item>
                </a-col>
                <a-col :span="6">
                  <a-form-item label="截止注册日期" name="endRegisterTime">
                    <a-date-picker
                      v-model:value="formState.data.endRegisterTime"
                      placeholder="选择日期"
                      valueFormat="yyyy-MM-DD"
                      type="date"
                      class="w-100p"
                    />
                  </a-form-item>
                </a-col>
                <a-col :span="6">
                  <a-form-item label="上课地点" name="classPlace">
                    <a-input
                      v-model:value="formState.data.classPlace"
                      placeholder="请输入"
                    />
                  </a-form-item>
                </a-col>
                <a-col :span="6">
                  <a-form-item label="课程详情链接" name="addressUrl">
                    <a-input
                      v-model:value="formState.data.addressUrl"
                      placeholder="请输入"
                      maxlength="100"
                    />
                  </a-form-item>
                </a-col>
              </a-row>
            </a-card>
            <a-card title="上课时段">
              <a-row>
                <a-col :span="6">
                  <a-form-item label="课程形式" name="shape">
                    <a-select show-search v-model:value="formState.data.shape" placeholder="请选择">
                      <a-select-option v-for="dict in dictLists.data[dictEnum.COURSE_SHIFT_SHAPE]"
                                       :key="dict.id"
                                       :value="dict.value">{{dict.label}}</a-select-option>
                    </a-select>
                  </a-form-item>
                </a-col>
                <a-col :span="6">
                  <a-form-item label="学校时区" name="timeZone">
                    <a-select show-search v-model:value="formState.data.timeZone" placeholder="请选择">
                      <a-select-option v-for="dict in dictLists.data[dictEnum.TIME_ZONE]"
                                       :key="dict.value"
                                       :value="dict.value">{{dict.label}}</a-select-option>
                    </a-select>
                  </a-form-item>
                </a-col>
                <a-col :span="6">
                  <a-form-item label="开始日期" name="startTime">
                    <a-date-picker
                      v-model:value="formState.data.startTime"
                      valueFormat="YYYY-MM-DD"
                      placeholder="请选择"
                    />
                  </a-form-item>
                </a-col>
                <a-col :span="6">
                  <a-form-item label="结束日期" name="endTime">
                    <a-date-picker
                      v-model:value="formState.data.endTime"
                      valueFormat="YYYY-MM-DD"
                      placeholder="请选择"
                    />
                  </a-form-item>
                </a-col>
                <a-col :span="6">
                  <a-form-item label="课程时长(周)" name="duration">
                    <a-input-number style="width: 100%" v-model:value="formState.data.duration" placeholder="请输入" :min="0" :max="10000" />
                  </a-form-item>
                </a-col>
                <a-col :span="18">
                  <a-form-item label="上课时间" name="courseHours" :label-col="{ span: 3 }">
                    <a-textarea v-model:value="formState.data.courseHours" :maxlength="500" :rows="1" placeholder="请输入"/>
                  </a-form-item>
                </a-col>
                <a-col :span="18">
                  <a-form-item label="备注" name="remark" :label-col="{ span: 3 }">
                    <a-textarea v-model:value="formState.data.remark" :maxlength="500" :rows="2" placeholder="请输入"/>
                  </a-form-item>
                </a-col>
              </a-row>
            </a-card>
          </a-form>
        </a-col>
      </a-row>
    </page-layout>
    <BasicTableModal
      v-model:visible="modalConfig.visible"
      v-if="modalConfig.visible"
      :columns="modalConfig.columns"
      :fetchAjax="modalConfig.api"
      :searchParams="modalConfig.searchParams"
      :searchForm="modalConfig.searchForm"
      :title="modalConfig.title"
      @selectUniversity="
        value => selectItem(value, modalConfig.type, modalConfig.currentIndex)
      "
    />
  </a-spin>
</template>
<script>
export default {
  name: "curriculum-price-add"
}
</script>
<script setup>
import { reactive, ref, onMounted, onActivated } from "vue";
import { upload } from "@/api/module/oss";
import BasicTableModal from "@/component/basic-table-modal";
import { page as schoolPage } from "@/api/module/school";

import { page as projectPage } from "@/api/module/project"; // 项目
import { page as userPage } from "@/api/module/user"; // 联系人
import { page as taPage } from "@/api/module/ta"; // Ta
import { page as professorPage } from "@/api/module/professor"; // 教授
import { page as coursePage } from "@/api/module/courseBaseInfo"; // 课程
import { page as termPage } from "@/api/module/term-manage"; // 学期
import { page as schPage } from "@/api/module/school"; // 学校
import { page as teachingPage } from "@/api/module/teaching-material"; // 教材
import {
  save as projectSave,
  update,
  selectById
} from "@/api/module/curriculum-price";
import dictEnum from "@/const/dict";
import { getDictByCodesReturnObj } from "@/tools/get-dict";
import { message } from "ant-design-vue";
import { useRouter, useRoute } from "vue-router";
import moment from "moment";
import mixin from '@/mixins'

const textareaRows = 3;
const labelCol = { span: 9 };
const endDate0 = ref()
const { returnRoute } = mixin.setup()

const formState = reactive({
  uploadImgLoading: false,
  buttons: [
    {
      name: "save",
      event: () => save(),
      type: "primary",
      code: ""
    },
    {
      name: "reset",
      event: () => resetForm(),
      code: ""
    }
  ],
  data: {
    shiftCode: "",
    schName: "",
    schShiftCode: '',
    schId: "",

    projectName: "", // 项目名称
    
    taName: "",
    taId: "",

    professorId: "", // 教授

    professorName: "",
    projectAddress: "",
    maximumEnrollment: "", // 最多招生人数
    classPlace: "", // 上课地点

    price: "", // 价格
    state: '1'
  }
});
const rules = {
  projectName: [
    {
      required: true,
      message: "请选择项目",
      trigger: "change"
    }
  ],
  cbiName: [
    {
      required: true,
      message: "请选择课程名称",
      trigger: "change"
    }
  ],
  price: [
    {
      required: false,
      message: "请输入价格",
      trigger: "blur"
    },
    {
      pattern: /(^[1-9]([0-9]+)?(\.[0-9]{1,2})?$)|(^(0){1}$)|(^[0-9]\.[0-9]{1,2}?$)/,
      message: '请输入正确的金额且金额小数点后保留两位',
      trigger: 'blur'
    }
  ],
};
const router = useRouter();
const route = useRoute();
const formRef = ref(null);
let dictLists = reactive({
  data: {}
});

const modalConfig = reactive({
  api: schoolPage,
  type: "",
  title: '学校名称',
  visible: false,
  columns: [],
  currentIndex: undefined,
  searchParams: {},
  searchForm: [],
  schoolColumns: [
    { dataIndex: "code", key: "code", title: "学校编码" },
    { dataIndex: "schoolEnName", key: "schoolEnName", title: "学校名称" },
    {
      dataIndex: "schFollowUpProgress",
      key: "schFollowUpProgress",
      title: "跟进进度",
      cellRender: (record, data) => {
        if (dictLists.data[dictEnum.FOLLOW_PROGRESS]) {
          const item = dictLists.data[dictEnum.FOLLOW_PROGRESS].find(
            v => v.value == data
          );
          return item ? item.label : "";
        }
        return "";
      }
    }
  ],
  schoolSearch: [
    { type: "input", key: "code", label: "学校编码" },
    { type: "input", key: "schoolEnName", label: "学校名称" },
  ],
  userColumns: [
    { dataIndex: "nickname", key: "nickname", title: "用户名称" },
    { dataIndex: "deptName", key: "deptName", title: "所属部门" },
    { dataIndex: "postName", key: "postName", title: "职位" }
  ],
  userSearch: [
    { type: "input", key: "nickname", label: "用户名称" },
  ],
  contactColumns: [
    { dataIndex: "code", key: "code", title: "联系人编码" },
    { dataIndex: "contactsName", key: "contactsName", title: "联系人姓名" },
    { dataIndex: "contactsPosition", key: "contactsPosition", title: "职位" },
    {
      dataIndex: "contactsDepartment",
      key: "contactsDepartment",
      title: "所属部门"
    }
  ],
  contactSearch: [
    { type: "input", key: "contactsName", label: "联系人姓名" },
    { type: "input", key: "code", label: "联系人编码" },
  ],
  schNameColumns: [
    { dataIndex: "code", key: "code", title: "项目编码" },
    { dataIndex: "projectName", key: "projectName", title: "项目名称" },
    { dataIndex: "projectAddress", key: "projectAddress", title: "项目地址" },
    {
      dataIndex: "schName",
      key: "schName",
      title: "合作学校名称"
    }
  ],
  teachingColumns: [
    { dataIndex: "tmName", key: "tmName", title: "教材名" },
    { dataIndex: "authorName", key: "authorName", title: "作者名" },
    { dataIndex: "press", key: "press", title: "出版社"},
    { dataIndex: "createBy", key: "createBy", title: "创建人" },
    { dataIndex: "createTime", key: "createTime", title: "创建时间" },
  ],
  teachingSearch: [
    { key: "tmName", type: "input", label: "教材名", placeholder: '请输入教材名'},
    { key: "press", type: "input", label: "出版社", placeholder: '请输入出版社'},
  ],
  schNameSearch: [
    { type: "input", key: "code", label: "项目编码" },
    { type: "input", key: "projectName", label: "项目名称" },
  ],
  semesterColumns: [
    { dataIndex: "semesterName", key: "semesterName", title: "学期名称" },
    { dataIndex: "createTime", key: "createTime", title: "创建时间" },
    {
      dataIndex: "id",
      key: "id",
      title: "学期id"
    }
  ],
  semesterSearch: [
    { type: "input", key: "semesterName", label: "学期名称" },
  ],
  cbiNameColumns: [
    { dataIndex: "code", key: "code", title: "课程编码" },
    { dataIndex: "courseName", key: "courseName", title: "课程名称" },
    { dataIndex: "createTime", key: "createTime", title: "创建时间" },
  ],
  cbiNameSearch: [
    { type: "input", key: "courseName", label: "课程名称" },
    { type: "input", key: "code", label: "课程编码" },
  ],
  professorColumns: [
    { dataIndex: "code", key: "code", title: "教授编码" },
    { dataIndex: "name", key: "name", title: "教授名字" },
    { dataIndex: "phoneNumbe", key: "phoneNumbe", title: "电话" }
  ],
  professorSearch: [
    { type: "input", key: "name", label: "教授名字" },
    { type: "input", key: "code", label: "教授编码" },
  ],
  taNameColumns: [
    { dataIndex: "code", key: "code", title: "助教编码" },
    { dataIndex: "taName", key: "taName", title: "助教名称" },
    { dataIndex: "createTime", key: "createTime", title: "创建时间" },
    { dataIndex: "taPhone", key: "taPhone", title: "电话" },
    { dataIndex: "taEmail", key: "taEmail", title: "邮箱" },
    { dataIndex: "taMajor", key: "taMajor", title: "Ta科目" }
  ],
  taNameSearch: [
    { type: "input", key: "taName", label: "助教名称" },
    { type: "input", key: "code", label: "助教编码" },
  ],
});
// 筛选弹窗api和列表数据
const openDialog = (type, _index) => {
  if (type == 'cbiName' && !formState.data.schId) {
    return message.warning('请先选择项目名称')
  }
  modalConfig.currentIndex = _index;
  modalConfig.visible = true;
  modalConfig.type = type;
  type == 'cbiName'
    ? (modalConfig.searchParams = {schId: formState.data.schId})
    : (modalConfig.searchParams = {})
  modalConfig.api =
    type === "schName" // 项目名称
      ? projectPage
      : type === "cbiName" // 课程
      ? coursePage
      : type === "taName" // Ta
      ? taPage
      : type === "semesterName" // 学期
      ? termPage
      : type === "professorName" // 教授
      ? professorPage
      : type === "schoolName" // 学校
      ? schPage
      : type === "teaching" // 教材
      ? teachingPage
      : userPage;
  modalConfig.title =
    type === "schName" // 项目名称
      ? '选择项目'
      : type === "cbiName" // 课程
      ? '选择课程'
      : type === "taName" // Ta
      ? '选择助教'
      : type === "semesterName" // 学期
      ? '选择学期'
      : type === "professorName" // 教授
      ? '选择教授'
      : type === "schoolName" // 学校
      ? '选择学校'
      : type === "teaching" // 教材
      ? '选择教材'
      : '';
  modalConfig.columns =
    type === "schName"
      ? modalConfig.schNameColumns
      : type === "semesterName"
      ? modalConfig.semesterColumns
      : type === "cbiName"
      ? modalConfig.cbiNameColumns
      : type === "professorName"
      ? modalConfig.professorColumns
      : type === "taName"
      ? modalConfig.taNameColumns
      : type === 'schoolName'
      ? modalConfig.schoolColumns
      : type === 'teaching'
      ? modalConfig.teachingColumns
      : modalConfig.taNameColumns;
  modalConfig.searchForm =
    type === "schName"
      ? modalConfig.schNameSearch
      : type === "semesterName"
      ? modalConfig.semesterSearch
      : type === "cbiName"
      ? modalConfig.cbiNameSearch
      : type === "professorName"
      ? modalConfig.professorSearch
      : type === "taName"
      ? modalConfig.taNameSearch
      : type === 'schoolName'
      ? modalConfig.schoolSearch
      : type === 'teaching'
      ? modalConfig.teachingSearch
      : modalConfig.taNameSearch;
};


const save = () => {
  formRef.value.validate().then(() => {
    formState.uploadImgLoading = true;
    saveItem(formState.data);
  });
};

const editItem = data => {
  update(data)
    .then(res => {
      if (res.code === 200) {
        message.success(res.message);
        returnRoute()
      }
      if (res.code === 500)
        return message.error(res.msg || "编辑失败，服务器错误");
      formState.uploadImgLoading = false;
    })
    .catch(() => (formState.uploadImgLoading = false));
};

const saveItem = data => {
  projectSave(data)
    .then(res => {
      formState.uploadImgLoading = false;
      if (res.code === 200) {
        message.success('保存成功');
        returnRoute()
      }
      if (res.code === 500)
        return message.error(res.msg || "新增失败，服务器错误");
    })
    .catch(() => (formState.uploadImgLoading = false));
};

const resetForm = () => {
  formRef.value.resetFields();
};

const selectItem = (value, type, index) => {
  if (type === "schName") {
    // 项目名称
    formState.data.projectName = value.projectName;
    formState.data.projectId = value.id;
    formState.data.schName = value.schName;
    formState.data.schId = value.schId;
    formState.data.cbiName = "";
    formState.data.cbiId = "";
    // formState.data.responsiblePersonName = value.responsiblePersonName;
  }
  if (type === "cbiName") {
    // 课程
    formState.data.cbiName = value.courseName;
    formState.data.courseName = value.courseName;
    formState.data.typeId = value.typeId;
    formState.data.courseCode = value.courseCode;
    formState.data.cbiId = value.id;
    // formState.data.disciplineId = value.disciplineId;
    // formState.data.disciplineName = value.disciplineName;
  }
  if (type === "taName") {
    // Ta
    formState.data.taName = value.taName;
    formState.data.taId = value.id;
  }
  if (type === "semesterName") {
    // 学期
    formState.data.semesterName = value.semesterName;
    formState.data.semesterId = value.id;
  }
  if (type === "professorName") {
    // 教授
    formState.data.professorName = value.name;
    formState.data.professorId = value.id;
  }
  if (type === "schoolName") {
    // 学校
    formState.data.schName = value.schoolEnName;
    formState.data.schId = value.id;
    formState.data.projectName = '';
    formState.data.responsiblePersonName = '';
    formState.data.cbiName = '';
    formState.data.cbiId = '';
  }
  if (type === "teaching") {
    // 学校
    formState.data.teachingName = value.tmName;
    formState.data.teachingId = value.id;
    formState.data.tmIsbn = value.tmIsbn;
  }

};

onActivated(async () => {
  dictLists.data = await getDictByCodesReturnObj([
    dictEnum.FOLLOW_PROGRESS,
    dictEnum.WEEK,
    dictEnum.ENABLE,
    dictEnum.SHAPE,
    dictEnum.COURSE_SHIFT_SHAPE,
    dictEnum.TIME_ZONE,
  ]);
  formRef.value.resetFields();
  if (route.query.id) {
    selectById({
      id: route.query.id
    }).then(res => {
      if (res.code === 500) return message.error(res.msg || "服务器错误");
      if (res.code === 200) {
        res.data.startRegisterTime = res.data.startRegisterTime
                                      ? moment(res.data.startRegisterTime).format('YYYY-MM-DD')
                                      : ''
        res.data.endRegisterTime = res.data.endRegisterTime
                                        ? moment(res.data.endRegisterTime).format('YYYY-MM-DD')
                                        : ''
        res.data.startTime = res.data.startTime
                                        ? moment(res.data.startTime).format('YYYY-MM-DD')
                                        : ''
        res.data.endTime = res.data.endTime
                                        ? moment(res.data.endTime).format('YYYY-MM-DD')
                                        : ''
        formState.data = {
          ...formState.data,
          ...res.data
        };
        formState.data.price = formState.data.price ? formState.data.price + '' : ''
      }
    });
  }
});
</script>

<style lang="less" scoped>
.add-project-box {
  .pointer-input {
    /deep/.ant-input {
      cursor: pointer;
    }
  }
}

.times {

  /deep/ .ant-form-item-control-input {
    max-width: 100px;
  }
}
</style>
